package com.xuruzi.demo.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;


import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Created by xuruzi on 2020/3/27.
 */
public class NetWorkCenter {
    private static final Logger logger = LoggerFactory.getLogger(NetWorkCenter.class);
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    public static BaseResponse get(String url){
        BaseResponse[] responses = new BaseResponse[]{null};
        doGetRequest(url,null,new ResponseCallback(){
            @Override
            public void onResponse(int resultCode, String result) {
                if(resultCode == 200){
                    BaseResponse baseResponse = JSON.parseObject(result,BaseResponse.class);
                    if(baseResponse != null && StringUtils.isEmpty(baseResponse.getErrcode())){
                        baseResponse.setErrcode("0");
                    }
                    baseResponse.setErrmsg(result);
                    responses[0] = baseResponse;
                }else {
                    responses[0] = new BaseResponse();
                    responses[0].setErrcode(String.valueOf(resultCode));
                    responses[0].setErrmsg("请求失败");
                }
            }
        });

        return responses[0];
    }

    public static void doGetRequest(String url,Map<String, String> paramMap,ResponseCallback callback){

        //拼接请求参数
        String paramData = null;
        if(paramMap != null && !paramMap.isEmpty()){
            StringBuilder stringBuilder = new StringBuilder();
            Iterator iterator = paramMap.entrySet().iterator();
            while(iterator.hasNext()){
                Entry entry = (Entry)iterator.next();
                stringBuilder
                        .append((String) entry.getKey())
                        .append("=")
                        .append((String)entry.getValue())
                        .append("&");
            }
            paramData = stringBuilder.substring(0,stringBuilder.length()-1);//最后一个&字符需去掉
        }

        if(url != null && !url.isEmpty()){
            logger.info("=====请求开始:{}", url);
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(10000)
                    .setConnectionRequestTimeout(10000)
                    .setSocketTimeout(10000)
                    .build();
            CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
            String newUrl = url;
            if(paramData != null && !paramData.isEmpty()){
                newUrl += "?" + paramData;
            }
            Object request = new HttpGet(newUrl);//拼接参数后的地址
            CloseableHttpResponse response = null;
            try {
                long currentTimeMillis = System.currentTimeMillis();
                response = client.execute((HttpUriRequest) request);
                long excuteTime = System.currentTimeMillis() - currentTimeMillis;
                logger.info("本次请求{}耗时:{}毫秒", newUrl, excuteTime);
                int resultCode = response.getStatusLine().getStatusCode();
                HttpEntity httpEntity = response.getEntity();
                String result = EntityUtils.toString(httpEntity, UTF_8);
                if(200 == resultCode){
                    logger.info("=====请求成功====");
                    logger.info("响应返回结果:");
                    logger.info(result);
                    callback.onResponse(resultCode, result);
                }

            }catch (ClientProtocolException e1){
                callback.onResponse(500,e1.toString());
            }catch (IOException e2){
                callback.onResponse(500,e2.toString());
            }finally {
                if(null != request && !((HttpUriRequest)request).isAborted()) {
                    ((HttpUriRequest)request).abort();
                }
                HttpClientUtils.closeQuietly(client);
                HttpClientUtils.closeQuietly(response);
            }
        }else {
            logger.warn("url不能为空");
        }
    }


    public interface ResponseCallback {
        void onResponse(int resultCode, String result);
    }
}
